<?php


namespace app\common\model;


class User extends Base
{
    public static $jwtSecret = "645654321asdfsadf";

    public function getTokenAttr()
    {
        $header = [
            'type' => 'JWT',
            'alg' => 'HS256'
        ];
        $header = base64_encode(json_encode($header));
        $payload = [
            "identity" => ["id" => $this->id],
            "exp" => date("Y-m-d H:i:s", strtotime("1 month")),
        ];
        $payload = base64_encode(json_encode($payload));

        $secret = self::$jwtSecret;
//        echo $secret;exit;
        $sign = hash_hmac("sha256", $header . "." . $payload, $secret);
        return implode(".", [$header, $payload, $sign]);
    }

    public static function getModelByToken()
    {
        $token = self::getToken();

        $tokenArr = explode('.', $token);

        if (count($tokenArr) != 3) {
            return null;
        }
        list($header, $payLoad, $sign) = $tokenArr;
        $sign2 = hash_hmac('sha256', $header . '.' . $payLoad, self::$jwtSecret);
        if ($sign !== $sign2) {
            return null;
        }
        $payLoadArr = json_decode(base64_decode($payLoad), true);
        if (strtotime($payLoadArr["exp"]) < time()) {

            return null;
        }
        $model = self::where(["id" => $payLoadArr["identity"]["id"]])->find();

        return $model;
    }

    /**
     * 获取token
     * @return mixed|null
     */
    public static function getToken()
    {
        $token = null;
        if (!$token) {
            //from header
            $headers = \getallheaders();
//            print_r($headers);exit;
            if ($headers) {
                foreach ($headers as $key => $value) {
                    if (strtolower($key) == strtolower("X-Token")) {
                        $token = $value;
                        break;
                    }
                }
            }
        }
        if (!$token) {
            //from url
            if (isset($_REQUEST["token"])) {
                $token = $_REQUEST["token"];
            }
        }
        return $token;
    }
}
